//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using SPUserPoll.Business.Components;
using SPUserPoll.Presentation.WebParts.UserControls;

namespace SPUserPoll.Presentation.WebParts
{
    public class PollDisplayWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        #region web part properties
        private DateTime _creationDate = new DateTime(2000, 1, 1, 1, 0, 0);

        /// <summary>
        /// Property that contains the poll creation date
        /// </summary>
        /// <value>The creation date.</value>
        [WebBrowsable(false)]
        [WebDisplayName("Poll creation date")]
        [WebDescription("Creation date of the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public DateTime SPUserPollCreationDate
        {
            get { return _creationDate; }
            set { _creationDate = value; }
        }

        private string _pollQuestion;

        /// <summary>
        /// Property that contains the poll question
        /// </summary>
        /// <value>The question.</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll question")]
        [WebDescription("Description of the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public string SPUserPollQuestion
        {
            get { return _pollQuestion; }
            set { _pollQuestion = value; }
        }

        private string _pollTitle;

        /// <summary>
        /// Property that contains the poll description
        /// </summary>
        /// <value>The title</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll title")]
        [WebDescription("Title of the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public string SPUserPollTitle
        {
            get { return _pollTitle; }
            set
            {
                _pollTitle = value;
                //update our webpart title in case it is the default spuserpoll caption
                if (this.Title == "SPUserPoll" && value != "SPUserPoll")
                    this.Title = value;
            }
        }

        private DateTime _pollClosingDate;

        /// <summary>
        /// Property that contains the poll closing date
        /// </summary>
        /// <value>A closing date for the poll.</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll closing date")]
        [WebDescription("Closing date for the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public DateTime SPUserPollClosingDate
        {
            get { return _pollClosingDate; }
            set { _pollClosingDate = value; }
        }

        private bool _pollPublished = false;

        /// <summary>
        /// Property that stores the published status
        /// </summary>
        /// <value>The poll published status</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll is published")]
        [WebDescription("Is the poll currently published")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool SPUserPollPublished
        {
            get { return _pollPublished; }
            set { _pollPublished = value; }
        }

        private string _pollOwner = null;

        /// <summary>
        /// Property that contains the owner / creator of the poll
        /// </summary>
        /// <value>The owner</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll owner")]
        [WebDescription("Creator or owner of the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public string SPUserPollOwner
        {
            get { return _pollOwner; }
            set { _pollOwner = value; }
        }


        private Types.PollResultType _pollResultType = Types.PollResultType.Count;

        /// <summary>
        /// Property that contains the result type of the poll
        /// </summary>
        /// <value>The owner</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll result label")]
        [WebDescription("Information to show in the result label.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public Types.PollResultType SPUserPollResultType
        {
            get { return _pollResultType; }
            set { _pollResultType = value; }
        }

        private bool _allowMultipleAnswers;

        /// <summary>
        /// Property to define if multiple answers are allowed.
        /// </summary>
        /// <value>The value</value>
        [WebBrowsable(true)]
        [WebDisplayName("Multiple Answers")]
        [WebDescription("Allow users to select multiple answers.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool SPUserPollAllowMultipleAnswers
        {
            get
            {
                return _allowMultipleAnswers;
            }
            set
            {
                _allowMultipleAnswers = value;
            }
        }

        private bool _anonymousResults;

        /// <summary>
        /// Property that stores if the poll is anononymous
        /// </summary>
        /// <value>The value</value>
        [WebBrowsable(true)]
        [WebDisplayName("Anonymous votes")]
        [WebDescription("Vote results are stored anonymous.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool SPUserPollAnonymousVotes
        {
            get
            {
                return _anonymousResults;
            }
            set
            {
                _anonymousResults = value;
            }
        }


        private bool _hideResultPreview = false;

        /// <summary>
        /// Property that stores if the poll is anononymous
        /// </summary>
        /// <value>The value</value>
        [WebBrowsable(true)]
        [WebDisplayName("Hide view results link")]
        [WebDescription("Hide the view results link for non admin users.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool SPUserPollHidePreviewResponsesLink
        {
            get
            {
                return _hideResultPreview;
            }
            set
            {
                _hideResultPreview = value;
            }
        }


        private string _pollID;

        /// <summary>
        /// Property that contains the poll ID
        /// </summary>
        /// <value>The id</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll ID")]
        [WebDescription("UniqueID of the poll.")]
        [System.ComponentModel.Category("Poll settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public string SPUserPollID
        {
            get
            {
                if (string.IsNullOrEmpty(_pollID))
                {
                    _pollID = this.ID;
                }
                return _pollID;
            }
            set
            {
                _pollID = value;
            }
        }

        private Types.PollResultDisplay _pollResultDisplay = Types.PollResultDisplay.Textual;

        /// <summary>
        /// Property that stores how the poll results are displayed
        /// </summary>
        /// <value>The owner</value>
        [WebBrowsable(true)]
        [WebDisplayName("Poll chart type")]
        [WebDescription("How to display the results.")]
        [System.ComponentModel.Category("Chart settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public Types.PollResultDisplay SPUserPollResultDisplay
        {
            get { return _pollResultDisplay; }
            set { _pollResultDisplay = value; }
        }



        private int _chartHeight = 200;

        /// <summary>
        /// Property that contains the height of the chart
        /// </summary>
        /// <value>The height</value>
        [WebBrowsable(true)]
        [WebDisplayName("Chart height")]
        [WebDescription("Height of the chart.")]
        [System.ComponentModel.Category("Chart settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public int SPUserPollChartHeight
        {
            get
            {
                return _chartHeight;
            }
            set
            {
                _chartHeight = value;
            }
        }

        private int _chartWidth = 200;

        /// <summary>
        /// Property that contains the width of the chart
        /// </summary>
        /// <value>The width</value>
        [WebBrowsable(true)]
        [WebDisplayName("Chart width")]
        [WebDescription("Width of the chart.")]
        [System.ComponentModel.Category("Chart settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public int SPUserPollChartWidth
        {
            get
            {
                return _chartWidth;
            }
            set
            {
                _chartWidth = value;
            }
        }

        private bool _chartBackground = false;

        /// <summary>
        /// Property that stores the published status
        /// </summary>
        /// <value>The poll published status</value>
        [WebBrowsable(true)]
        [WebDisplayName("Gradient background")]
        [WebDescription("Show a gradient background")]
        [System.ComponentModel.Category("Chart settings")]
        [Personalizable(PersonalizationScope.Shared)]
        public bool SPUserPollShowChartBackground
        {
            get { return _chartBackground; }
            set { _chartBackground = value; }
        }
        #endregion

        #region globals
        private int _userIsAdmin = -1;

        /// <summary>
        /// Central check to remember if the user = admin
        /// </summary>
        public bool UserIsAdmin
        {
            get {
                if (_userIsAdmin == -1)
                {
                    if (User.HasAdminRights())
                        _userIsAdmin = 1;
                    else
                        _userIsAdmin = 0;
                }
                if (_userIsAdmin == 1)
                    return true;
                else
                    return false;
            }
        }

        private int _userIsDesigner = -1;

        public bool UserIsDesigner
        {
            get {
                if (_userIsDesigner == -1)
                {
                    if (User.HasDesignerRights())
                        _userIsDesigner = 1;
                    else
                        _userIsDesigner = 0;
                }
                if (_userIsDesigner == 1)
                    return true;
                else
                    return false;
            }
        }

        private int _userIsOwner = -1;

        public bool UserIsOwner
        {
            get {
                if (_userIsOwner == -1)
                {
                    if (SPUserPollOwner != null && SPUserPollOwner.ToLower() == User.GetUserLogin().ToLower())
                        _userIsOwner = 1;
                    else
                        _userIsOwner = 0;
                }
                if (_userIsOwner == 1)
                    return true;
                else
                    return false;
 
            }
        }
        #endregion

        #region render
        protected override void CreateChildControls()
        {
            bool showPollConfiguration = false;
            bool showPoll = false;

            //Add the CSS of the webpart to the page
            CssRegistration.Register("/_layouts/STYLES/SPUserPoll.css");

            if (SPUserPollPublished == false)
            {
                //only show the poll to the created user when the status is still unpublished
                if (SPUserPollOwner!=null && SPUserPollOwner.ToLower() == User.GetUserLogin().ToLower())
                    showPollConfiguration = true;

                //also show the poll in case the user is an Administrator
                if (UserIsAdmin)
                    showPollConfiguration = true;

                //register the poll to the current owner 
                if (SPUserPollOwner == null)
                {
                    //register this control to the current user
                    SPUserPollOwner = User.GetUserLogin();
                    //write it to the property on the page settings
                    ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), this.ID, "SPUserPollOwner", SPUserPollOwner);
                    ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), this.ID, "SPUserPollPublished", SPUserPollPublished);
                    showPollConfiguration = true; 
                }
            }
            else if (SPUserPollPublished == true)
            {
                //poll is active
                showPoll = true;
            }

            if (showPollConfiguration == true)
            {
                //show the poll configuration screen to the poll owner
                this.Hidden = false;
                PollDisplayControl wp = (PollDisplayControl)Page.LoadControl(@"~/_CONTROLTEMPLATES/SPUserPoll/PollDisplayControl.ascx");
                Controls.Add(wp);
            }
            else if (showPoll == true)
            {
                this.Hidden = false;
                bool userHasAlreadyVoted = true;

                //decide if we show the poll or that we show the results...
                //Only check for this parameter incase the poll has not been expired. If the poll is closed we will only show the results
                if (Business.Components.DateAndTime.IsPollExpired(SPUserPollClosingDate) == false)
                {
                    string userName = User.GetUserLogin();
                    userHasAlreadyVoted = User.DidTheUserVote(userName, SPUserPollID, SPUserPollAnonymousVotes);
                }

                if (userHasAlreadyVoted == false)
                {
                    //show the poll 
                    PollAnswerControl wp = (PollAnswerControl)Page.LoadControl(@"~/_CONTROLTEMPLATES/SPUserPoll/PollAnswerControl.ascx");
                    Controls.Add(wp);
                }
                else
                {
                    //User has already voted. We show the poll results
                    PollResultControl wp = (PollResultControl)Page.LoadControl(@"~/_CONTROLTEMPLATES/SPUserPoll/PollResultControl.ascx");
                    Controls.Add(wp);
                }
            }
            else
            {
                //the poll is not published yet. hide the poll
                this.Hidden = true;
            }
        }
        #endregion
    }
}
